package com.oneonefive.educationsystem.controller;

import com.oneonefive.educationsystem.domain.Login;
import com.oneonefive.educationsystem.domain.StudentRequest;
import com.oneonefive.educationsystem.dto.Result;
import com.oneonefive.educationsystem.service.StudentRequestService;
import com.oneonefive.educationsystem.vo.StudentRequestVo;
import jakarta.annotation.Resource;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.sql.Date;
import java.time.LocalDate;

@RestController
@CrossOrigin
@RequestMapping("/stuReq")
public class StudentRequestController {
    @Resource
    StudentRequestService studentRequestService;

    @PostMapping()
    @PreAuthorize("hasAuthority('student')")
    public Result stuReqSave(@RequestBody StudentRequest studentRequest, Authentication authentication) {
        LocalDate currentDate = LocalDate.now();
        studentRequest.setDate(Date.valueOf(currentDate));
        Login principal = (Login) authentication.getPrincipal();
        Result setValue = studentRequestService.setValue(studentRequest, principal.getUser());
        if (!setValue.getSuccess()) {
            return setValue;
        }
        Result legitimacy = studentRequestService.legitimacy(studentRequest);
        if (!legitimacy.getSuccess()) {
            return legitimacy;
        }

        boolean success = studentRequestService.save(studentRequest);
        if (success) {
            return Result.ok("StudentRequest新增成功");
        }
        return Result.fail("StudentRequest新增失败");
    }

    @PutMapping()
    @PreAuthorize("hasAuthority('student')")
    public Result stuReqUpdate(@RequestBody StudentRequest studentRequest) {
        Result legitimacy = studentRequestService.legitimacy(studentRequest);
        if (!legitimacy.getSuccess()) {
            return legitimacy;
        }
        boolean success = studentRequestService.updateById(studentRequest);
        if (success) {
            return Result.ok("StudentRequest修改成功");
        }
        return Result.fail("StudentRequest修改失败");
    }

    //data:List<StudentRequest>
    @PostMapping("/1")
    @PreAuthorize("hasAuthority('student')")
    public Result stuReqList(@RequestBody StudentRequestVo studentRequestVo) {
        return studentRequestService.stuReqList(studentRequestVo);
    }

}
